<template>
  <cl-crud ref="Crud">
    <cl-row>
      <cl-refresh-btn />
      <cl-add-btn />
      <cl-multi-delete-btn />
      <cl-flex1 />
    </cl-row>

    <cl-row>
      <cl-table ref="Table">
        <template #column-image="{ scope }">
          <cl-image :src="scope.row.image" :width="60" :height="60" />
        </template>
        <template #column-categoryId="{ scope }">
          {{ getCategoryName(scope.row.categoryId) }}
        </template>
      </cl-table>
    </cl-row>

    <cl-upsert ref="Upsert">
      <template #slot-categoryId="{ scope }">
        <el-tree-select
          v-model="scope.categoryId"
          :data="categoryTree"
          :props="treeProps"
          clearable
          placeholder="请选择分类"
        />
      </template>
    </cl-upsert>
  </cl-crud>
</template>

<script lang="ts" setup>
import { useCrud, useTable, useUpsert } from "@cool-vue/crud";
import { ref, onMounted, nextTick } from "vue";
import { useCool } from "/@/cool";
import { useI18n } from "vue-i18n";

const { service } = useCool();
const { t } = useI18n();

// 分类树（用于选择所属分类）
const categoryTree = ref<any[]>([]);
const treeProps = { label: "name", value: "id", children: "children" };
const flatCategoryList = ref<any[]>([]);

function flattenTree(tree) {
  const result = [];
  const walk = (list) => {
    if (!Array.isArray(list)) return;
    for (const node of list) {
      result.push(node);
      if (node.children && node.children.length) walk(node.children);
    }
  };
  walk(tree);
  return result;
}

const fetchCategoryTree = async () => {
  const res = await service.base.goodsCategory.tree();
  categoryTree.value = res?.data ?? [];
  flatCategoryList.value = flattenTree(categoryTree.value);
};
onMounted(fetchCategoryTree);

const getCategoryName = (id: number) => {
  const item = flatCategoryList.value.find((c) => c.id === id);
  return item ? item.name : "—";
};

// cl-table 配置
const Table = useTable({
  columns: [
    { type: "selection", width: 60 },
    { label: t("主图"), prop: "image", width: 80, component: { name: "cl-image" } },
    { label: t("标题"), prop: "title", minWidth: 120 },
    {
      label: t("分类"),
      prop: "categoryId",
      minWidth: 120,
      formatter({ row }) {
        return getCategoryName(row.categoryId);
      },
    },
    { label: t("价格"), prop: "price", width: 100 },
    { label: t("详情"), prop: "description", minWidth: 150, showOverflowTooltip: true },
    { label: t("分站ID"), prop: "siteId", width: 80 },
    { label: t("创建时间"), prop: "createTime", minWidth: 140 },
    {
      type: "op",
      width: 200,
      buttons() {
        return ["edit", "delete"];
      },
    },
  ],
});

// cl-upsert 配置
const Upsert = useUpsert({
  dialog: { width: "700px" },
  items: [
    {
      prop: "title",
      label: t("标题"),
      required: true,
      component: { name: "el-input", props: { placeholder: t("请输入商品标题") } },
    },
    {
      prop: "categoryId",
      label: t("分类"),
      required: true,
      component: { name: "slot-categoryId" },
    },
    {
      prop: "image",
      label: t("主图"),
      required: true,
      component: {
        name: "cl-upload",
        props: { accept: "image/*", placeholder: t("上传商品图片") },
      },
    },
    {
      prop: "price",
      label: t("价格"),
      required: true,
      component: {
        name: "el-input-number",
        props: { min: 0, step: 0.01, placeholder: t("请输入价格") },
      },
    },
    {
      prop: "description",
      label: t("详情"),
      component: {
        name: "el-input",
        props: { type: "textarea", rows: 3, placeholder: t("请输入商品详情") },
      },
    },
    {
      prop: "siteId",
      label: t("分站ID"),
      required: true,
      component: {
        name: "el-input-number",
        props: { min: 1, placeholder: t("请输入分站ID") },
      },
    },
  ],
  async onOpened() {
    await fetchCategoryTree();
    await nextTick();
  },
});

// cl-crud 配置
const Crud = useCrud(
  {
    service: service.base.goods,
    onRefresh(params, { render }) {
      service.base.goods.page(params).then((res) => {
        render(res);
      });
    },
  },
  (app) => {
    app.refresh();
  }
);
</script>
